﻿using Blog.Core.Data;
using Blog.Core.Model.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Blog.Core.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MenusController : ControllerBase
    {
        private readonly BlogContext _context;

        public MenusController(BlogContext context)
        {
            _context = context;
        }

        // GET: api/Menu
        [HttpGet]
        public async Task<ActionResult<IEnumerable<MainMenu>>> GetMainMenus()
        {
            return await _context.MainMenus.ToListAsync();
        }

        // GET: api/Menu/5
        [HttpGet("{id}")]
        public async Task<ActionResult<MainMenu>> GetMainMenu(int id)
        {
            var mainMenu = await _context.MainMenus.FindAsync(id);

            if (mainMenu == null)
            {
                return NotFound();
            }

            return mainMenu;
        }

        // PUT: api/Menu/5
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPut("{id}")]
        public async Task<IActionResult> PutMainMenu(int id, MainMenu mainMenu)
        {
            if (id != mainMenu.ID)
            {
                return BadRequest();
            }

            _context.Entry(mainMenu).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MainMenuExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Menu
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<MainMenu>> PostMainMenu(MainMenu mainMenu)
        {
            _context.MainMenus.Add(mainMenu);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetMainMenu", new { id = mainMenu.ID }, mainMenu);
        }

        // DELETE: api/Menu/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteMainMenu(int id)
        {
            var mainMenu = await _context.MainMenus.FindAsync(id);
            if (mainMenu == null)
            {
                return NotFound();
            }

            _context.MainMenus.Remove(mainMenu);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool MainMenuExists(int id)
        {
            return _context.MainMenus.Any(e => e.ID == id);
        }
    }
}
